// pages/place_order/place_order.js
var common = require("../../../common/common.js").common;

var QQMapWX = require("../../../sdk/qqmap-wx-jssdk.min.js");

var util = require("../../../utils/util.js");

const {$Toast: $Toast} = require("../../../dist/base/index");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        showInfoTip: false,
        deliver_method: "self",
        arr_id: [],
        arr_count: [],
        goods: [],
        order_goods: [],
        totale_goods: 0,
        totale_price: 0,
        totale_price2: 0,
        all_price: 0,
        yunfei: 10,
        items: [],
        leader_id: 0,
        latitude: "31.997012",
        longitude: "120.861111",
        group: "",
        address: "",
        close_order: "",
        payment_status: 1,
        status: 0,
        leader_change: 2,
        leader_express: 2,
        color_header: "",
        color_main: "",
        color_minor: "",
        confirm_lead: 0,
        buy_info: [],
        form_id: "",
        discount_label: 1,
        choose_discount: -1,
        discount_alert: 0,
        discount: [],
        discount_use: 0,
        discount_unuse: 0,
        discount_price: 0,
        discount_id: "",
        discount_title: "",
        discount_id2: "",
        confirm: 0,
        discount_price2: 0,
        discounted_price: 0,
        click_time: 1,
        confirm_time: 1,
        rp_name: "",
        isIPX: "",
        choose_type: 1,
        other_money: 0,
        difference: 0,
        trans_for_free_barrier: "",
        on_off_trans_free: 0,
        typeBox: [],
        myleaderinfo: {
            leader_id: -1,
            leader_id_true: -1
        },
        time_id: "",
        group_id: "",
        //群接龙活动id
        isseckill: 0,
        isDiscount: 1,
        express: 0,
        //快递配送费
        // discount_money:0,
        refund: "",
        //满减
        no_refundGood: 0,
        //存储没有满减活动商品的总和
        refund_money: 0,
        radioCurrent: 0,
        color_gray: "#848484",
        //单选按钮未选中颜色
        payName: "余额",
        payWayList: [],
        payWayList1: [ {
            iconfonts: "icon-yue",
            //支付方式icon
            payWayName: "余额",
            //支付方式名称pay
            isChecked: true,
            //radio状态
            color: "#FFAE00",
            //icon颜色,
            isDisabled: false
        }, {
            iconfonts: "icon-weixinzhifu",
            payWayName: "微信支付",
            isChecked: false,
            color: "#45C144",
            isDisabled: false
        }, {
            //专项资金
            iconfonts: "icon-zijin",
            payWayName: "专项资金",
            isChecked: false,
            color: "#ff3d17",
            isDisabled: false
        } ],
        //支付方式
        balanceNum: 0,
        //余额金额
        balanceNumTip: "",
        isShowPay: false,
        //是否显示充值按钮
        getLeaderNum: 0,
        //请求团长接口次数
        balance_confirm: 0,
        //余额支付确认弹窗隐藏
        balanceSwitch: 0,
        //支付方式选择 不1为关闭
        componentStyle: {
            navigationTitle: "立即支付",
            goBack: 2
        },
        receiverInfo: {},
        goodsListStyle: {
            style: 2,
            screenFull: false,
            styleConfig: {
                backgroundColor: "#fff"
            }
        },
        payButtonDisabled: false,
        subscribeMessage: true,
        definePoster: false,
        integral_check: 0,
        group_id: "",
        weightTipShow: 0,
        total_packing_fee: 0,
        choose_delivery_index: 0,
        isDelivery: true,
        multiIndex: [ 0, 0 ],
        delivery_rangeArr: [],
        reach_time: ""
    },
    /**
   * 计算最终价格 商品总价(会员价)-满减-积分抵扣-红包+配送费+快递费
   * 
   */
    platPageAll: function() {
        let that = this;
        let all_price = that.data.all_price;
    },
    radioChange(e) {
        console.log(e);
        var data = this.data.payWayList;
        if (data[e.detail.value].payWayName == "专项资金" && this.data.isSpec_fund == 0) {
            wx.showModal({
                title: "提示",
                content: "专项资金只能购买专项资金指定商品，普通商品不能使用！",
                showCancel: false
            });
            return;
        }
        data.forEach((item, index) => {
            if (index == e.detail.value) {
                item.isChecked = true;
            } else {
                item.isChecked = false;
            }
        });
        this.setData({
            //radioCurrent: e.detail.value
            payWayList: data
        });
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        var isIPX = app.globalData.isIPX;
        console.log("isIPX:" + isIPX);
        this.setData({
            isIPX: isIPX,
            options: options
        });
        if (options.group_id) {
            this.setData({
                group_id: options.group_id
            });
        }
        if (options.status) {
            this.setData({
                status: options.status
            });
        }
        //秒杀方式，isseckill==1
                if (options.isseckill) {
            this.setData({
                isseckill: options.isseckill
            });
        }
        if (options.time_id) {
            this.setData({
                time_id: options.time_id
            });
        }
        let sku_item = options.sku_item;
        let arr = sku_item.split("|");
        var arr_id = [];
        var arr_count = [];
        var goods = [];
        var items = this.getItems(sku_item);
        //获取商品id数组
                var idBox = [];
        items.forEach((item, index) => {
            idBox.push(item.sku_id);
        });
        var totale_goods = 0;
        for (var i = 0; i < arr.length; i++) {
            arr_id.push(arr[i].split(",")[0]);
            arr_count.push(arr[i].split(",")[1]);
            goods[i] = [ arr[i].split(",")[0], arr[i].split(",")[1] ];
            totale_goods += parseInt(arr[i].split(",")[1]);
        }
        this.setData({
            arr_id: arr_id,
            arr_count: arr_count,
            goods: goods,
            totale_goods: totale_goods,
            items: items,
            //下单商品列表含单价和数量
            payment_status: 1,
            balanceNum: 0,
            balanceNumTip: "（余额：￥" + 0 + "）",
            idBox: idBox
        });
        this.vipStatus();
        this.getBase();
        this.getBalance();
        //获取余额
        // this.getMyLeaderInfo(); //我的团长信息
                this.getInfo();
        //下单信息 
                this.getCloseOrder();
        //?没找到用处
                this.getKilldis();
        //秒杀用处
                this.getTmplIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        this.getRecieverInfo().then(res => {
            // this.getRecieverAddress().then(res => {
            console.log("delivery_price" + this.data.delivery_price);
            this.getMyLeaderInfo(this.data.all_price3);
            //我的团长信息
            // });
                });
    },
    /** 
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    bindPickerChange: function(e) {
        var choose_delivery_index = e.detail.value;
        this.setData({
            choose_delivery_index: choose_delivery_index
        });
    },
    vipStatus: function() {
        var that = this;
        common.request({
            endpoint: "vipcard/vip-verify",
            method: "post",
            data: {},
            success: res => {
                var vipStatus = res.extra.vip_card;
                if (vipStatus == 1 || vipStatus == 2 || vipStatus == 3) {
                    //会员卡 0-没有 1-付费 2-消费 3-体验 -1-过期
                    vipStatus = 1;
                } else {
                    vipStatus = 0;
                }
                that.setData({
                    vipStatus: vipStatus,
                    vipLeaderExpress: res.extra.leader_express
                });
            },
            fail() {}
        });
    },
    onPageScroll(e) {
        var scrollTop = e.scrollTop;
        if (!scrollTop) {
            this.setData({
                componentOpcity: 0
            });
        } else if (scrollTop / 44 >= 1) {
            this.setData({
                componentOpcity: 1
            });
        } else {
            this.setData({
                componentOpcity: scrollTop / 44
            });
        }
    },
    getMyLeaderInfo: function(show_all_price) {
        console.log("show_all_price" + show_all_price);
        var that = this;
        var getLeaderNum = that.data.getLeaderNum + 1;
        var platPro = that.data.platPro;
        var delivery_type = that.data.delivery_type;
        that.setData({
            getLeaderNum: getLeaderNum
        });
        if (getLeaderNum == 1) {} else {
            console.log("第一次请求团长");
            common.request({
                endpoint: "leader/myleaderinfo",
                method: "post",
                data: {
                    leader_id_share: "",
                    openid: wx.getStorageSync("user").openid
                },
                success: res => {
                    //判断是否只有快递商品
                    //platPro是指团长类型的商品，如果有则判断是否存在团长
                    if (platPro.item.length > 0) {
                        if (res.extra.length == 0) {
                            if (this.data.leader_change == "1") {
                                wx.showModal({
                                    title: "提示",
                                    content: "您还没有选择" + that.data.leaderName + "，请先选择" + that.data.leaderName + "后再下单",
                                    showCancel: false,
                                    success(res) {
                                        if (res.confirm) {
                                            wx.redirectTo({
                                                url: "/pages/nearby_group2/nearby_group2"
                                            });
                                        }
                                    }
                                });
                            } else {
                                wx.showModal({
                                    title: "提示",
                                    content: "您还没有" + that.data.leaderName + "，请点击" + that.data.leaderName + "转发的小程序后下单！",
                                    showCancel: false,
                                    success(res) {
                                        if (res.confirm) {
                                            wx.reLaunch({
                                                url: "/pages/index/index"
                                            });
                                        }
                                    }
                                });
                            }
                        } else {
                            if (res.extra.trans_type.length == 0) {
                                wx.showModal({
                                    title: "提示",
                                    content: "该" + that.data.leaderName + "暂无提货方式",
                                    showCancel: false,
                                    success() {
                                        wx.navigateBack({});
                                    }
                                });
                            }
                        }
                    }
                    var platWay;
                    console.log("团长信息");
                    console.log(res.extra);
                    if (Object.prototype.toString.call(res.extra) === "[object Object]") {
                        if (res.extra.trans_type.length > 0) {
                            switch (res.extra.trans_type[0].type) {
                              case "0":
                                platWay = 2;
                                //团长配送
                                                                break;

                              case "1":
                                platWay = 1;
                                break;

                              case "2":
                                platWay = 3;
                                break;

                              default:
                                platWay = "";
                            }
                        } else {
                            platWay = 4;
                        }
                    }
                    console.log("存在团长0");
                    console.log(that.data.myleaderinfo);
                    //存在团长
                                        if (res.extra && Object.prototype.toString.call(res.extra) === "[object Object]") {
                        console.log("存在团长1");
                        console.log(res.extra.leader_id);
                        console.log(that.data.myleaderinfo.leader_id);
                        if (res.extra.leader_id != that.data.myleaderinfo.leader_id) {
                            if (res.extra.trans_type[0].pinkage == 1 && parseFloat(show_all_price) >= parseFloat(res.extra.trans_type[0].pinkage_price) || res.extra.trans_type[0].type == 0 && that.data.vipLeaderExpress == 1) {
                                var other_money = 0;
                            } else {
                                var other_money = parseFloat(res.extra.trans_type[0].cost).toFixed(2);
                            }
                            this.setData({
                                myleaderinfo: res.extra,
                                yunfei: res.extra.distribution_fee,
                                choose_type: res.extra.trans_type[0].type,
                                other_money: other_money,
                                trans_for_free_barrier: res.extra.trans_for_free_barrier,
                                //满额包邮金额
                                on_off_trans_free: res.extra.on_off_trans_free,
                                //满额包邮开关
                                typeBox: res.extra.trans_type,
                                platWay: platWay
                            });
                            //设置收货人信息
                            //that.setRecieverInfo(res.extra.trans_type[0].type);
                                                }
                        console.log("存在团长2");
                        console.log(other_money);
                    } else {
                        console.log("这里是不存在团长的情况下");
                        var other_money = 0;
                        this.setData({
                            myleaderinfo: res.extra,
                            yunfei: !res.extra.distribution_fee ? "" : res.extra.distribution_fee,
                            choose_type: !res.extra.trans_type ? 1 : res.extra.trans_type[0].type,
                            other_money: other_money,
                            trans_for_free_barrier: !res.extra.trans_for_free_barrier ? "" : res.extra.trans_for_free_barrier,
                            //满额包邮条件
                            on_off_trans_free: !res.extra.on_off_trans_free ? "" : res.extra.on_off_trans_free,
                            typeBox: !res.extra.trans_type ? "" : res.extra.trans_type,
                            platWay: platWay
                        });
                        //设置收货人信息
                        //that.setRecieverInfo(res.extra.trans_type[0].type);
                                        }
                    var leaderInfo = {
                        teamName: res.extra.title,
                        //团名
                        leaderName: res.extra.name,
                        //团长名称
                        phone: res.extra.phone,
                        //电话
                        address: res.extra.other,
                        //自提点
                        url: ""
                    };
                    that.setData({
                        leaderInfo: leaderInfo
                    });
                    var express = that.data.express;
                    var all_price = that.data.all_price;
                    var all_price2 = !that.data.all_price2 ? 0 : that.data.all_price2;
                    var other_money = that.data.other_money;
                    //配送费
                                        var trans_for_free_barrier = that.data.trans_for_free_barrier;
                    var platTotalPrice = that.data.platTotalPrice;
                    //平台商品价格
                                        var difference = parseFloat(trans_for_free_barrier) - parseFloat(show_all_price);
                    //满额条件与商品总金额的差值
                                        var on_off_trans_free = that.data.on_off_trans_free;
                    var typeBox = that.data.typeBox;
                    for (var i = 0; i < typeBox.length; i++) {
                        if (typeBox[i].type == 2) {
                            express = typeBox[i].cost;
                            that.setData({
                                express: express
                            });
                        } else if (typeBox[i].type == 0) {
                            var pinkage_price = typeBox[i].pinkage_price;
                            var pinkage = typeBox[i].pinkage;
                            var pinkage_other = typeBox[i].cost;
                            that.setData({
                                pinkage_price: pinkage_price,
                                pinkage_other: pinkage_other,
                                pinkage: pinkage
                            });
                        }
                    }
                    console.log("平台配送费");
                    console.log(other_money);
                    //平台配送，只有平台配送，并且满足满减条件，快递费为0  距离收费
                                        if (that.data.platPro.item.length == 0) {
                        console.log("无平台商品，平台配送费清0");
                        other_money = 0;
                        that.setData({
                            other_money: 0
                        });
                    } else if (typeBox.length >= 1 && that.data.choose_type == 2 && difference <= 0 && on_off_trans_free == 1) {
                        console.log("达到包邮，平台配送费清0");
                        other_money = 0;
                        that.setData({
                            other_money: 0
                        });
                    } else if (typeBox.length >= 1 && that.data.choose_type == 2 && (on_off_trans_free == 1 && difference > 0 || on_off_trans_free == 0)) {
                        if (delivery_type == 2) {
                            if (!that.data.isDelivery) {
                                //配送范围外
                                that.setData({
                                    payButtonDisabled: true,
                                    defferNum: that.data.isDeliveryTip
                                });
                            } else {
                                that.setData({
                                    payButtonDisabled: false,
                                    defferNum: "立即支付"
                                });
                                var other_money = that.data.delivery_price;
                            }
                        }
                    }
                    //初始化配送方式
                    // other_money = 0
                    // that.setData({
                    //   other_money: 0
                    // })
                    // let payExpressCost = that.data.payExpressCost;
                                        let totale_price = parseFloat(all_price) - parseFloat(that.data.refund_money) - parseFloat(that.data.discount_price2);
                    // let preference=parseFloat(that.data.discount_price2) + parseFloat(that.data.refund_money)+parseFloat(that.data.total_mem_level_discount)
                                        let preference = parseFloat(that.data.discount_price2) + parseFloat(that.data.refund_money);
                    if (that.data.integral_check == 1 && that.data.integral_status == 1) {
                        preference = parseFloat(preference) + parseFloat(that.data.total_discount);
                        totale_price = parseFloat(totale_price) - parseFloat(that.data.total_discount);
                    }
                    if (totale_price <= 0) {
                        totale_price = .01;
                    }
                    if (that.data.is_basic_pack == 1) {
                        //包装费
                        var total_packing_fee = parseFloat(that.data.basic_pack) + parseFloat(that.data.product_packing_fee);
                        this.setData({
                            total_packing_fee: parseFloat(total_packing_fee).toFixed(2)
                        });
                    }
                    totale_price = parseFloat(totale_price) + parseFloat(other_money) + parseFloat(that.data.payExpressCost) + parseFloat(that.data.total_packing_fee);
                    that.setData({
                        totale_price: totale_price.toFixed(2),
                        totale_price2: parseFloat(all_price).toFixed(2),
                        discounted_price: parseFloat(all_price).toFixed(2),
                        difference: difference.toFixed(2),
                        all_price: parseFloat(all_price).toFixed(2),
                        preference: parseFloat(preference).toFixed(2)
                    });
                    //计算是否超过包装费
                                        if (platWay == 2 && that.data.is_leader_weight == 1) {
                        //团长
                        var total_weight = that.data.total_weight * 1e3;
                        var leader_weight = that.data.leader_weight;
                        if (total_weight > leader_weight) {
                            var weightTip = "*重量：" + total_weight + "g" + " 超出配送限制(" + leader_weight + "g)无法支付";
                            this.setData({
                                payButtonDisabled: true,
                                weightTipShow: 1,
                                weightTip: weightTip
                            });
                        }
                    }
                    if (platWay == 3 && that.data.is_plat_weight == 1) {
                        //平台
                        var total_weight = that.data.total_weight * 1e3;
                        var plat_weight = that.data.plat_weight;
                        if (total_weight > plat_weight) {
                            var weightTip = "*重量：" + total_weight + "g" + " 超出配送限制(" + plat_weight + "g)无法支付";
                            this.setData({
                                payButtonDisabled: true,
                                weightTipShow: 1,
                                weightTip: weightTip
                            });
                        }
                    }
                    that.balanceIsOpen(totale_price.toFixed(2));
                    //如果有积分先选择积分，在选择红包
                    // that.getIntegralDiscount().then(() => {
                    //   //如果有可选，默认选第一个
                    //   if (that.data.discount_use&&that.data.totale_price>0.01) {
                    //     var discount = [];
                    //     var discount = that.data.discount;
                    //     discount = discount.filter(x => {
                    //       return x.flag == 1;
                    //     })
                    //     var e = {
                    //       currentTarget: {
                    //         dataset: {
                    //           id: discount[0].id,
                    //           price: discount[0].discount,
                    //           title: discount[0].title,
                    //           showIndex: 1 //首次进来需判断
                    //         }
                    //       }
                    //     }
                    //     that.choose_discount(e);
                    //   } else {
                    //     //判断余额
                    //     console.log("请求余额")
                    //     console.log(totale_price.toFixed(2), "1")
                    //     that.balanceIsOpen(totale_price.toFixed(2));
                    //   }
                    // });
                                }
            });
        }
    },
    getRecieverInfo() {
        let that = this;
        return new Promise((resolve, reject) => {
            var reciever = app.globalData.reciever;
            if (reciever) {
                that.setData({
                    recieverInfo: {
                        ...reciever,
                        url: "/addressManagerPackage/pages/addressList/addressList"
                    }
                });
                resolve();
            } else {
                common.request({
                    endpoint: "member/def_address",
                    method: "post",
                    data: {},
                    success(res) {
                        console.log(res, "reciever");
                        var data = res.extra;
                        if (data) {
                            var recieverInfo = {
                                receiverName: data.name,
                                //收货人名称
                                phone: data.phone,
                                //电话
                                address: data.city + " " + data.area,
                                //收货地址
                                city: data.city,
                                area: data.area,
                                wwb_street_id: data.wwb_street_id,
                                url: "/addressManagerPackage/pages/addressList/addressList"
                            };
                            app.globalData.reciever = recieverInfo;
                            that.setData({
                                recieverInfo: recieverInfo
                            });
                        } else {
                            var recieverInfo = {
                                url: "/addressManagerPackage/pages/addressList/addressList"
                            };
                            that.setData({
                                recieverInfo: recieverInfo
                            });
                        }
                        resolve();
                    },
                    fail(err) {}
                });
            }
        });
    },
    getRecieverAddress() {
        var that = this;
        return new Promise((resolve, reject) => {
            common.getAppBase().then(() => {
                wx.request({
                    url: "http://apis.map.qq.com/ws/geocoder/v1/",
                    method: "get",
                    data: {
                        address: that.data.recieverInfo.address,
                        key: that.data.appBase.location_key
                    },
                    success: function(res) {
                        if (res.data.status == 0) {
                            that.setData({
                                ["recieverInfo.lat"]: res.data.result.location.lat,
                                ["recieverInfo.lng"]: res.data.result.location.lng
                            });
                            if (that.data.delivery_type == 1) {
                                //固定收费
                                resolve();
                            } else {
                                //获取距离收费
                                common.request({
                                    endpoint: "set/plat-delivery",
                                    method: "post",
                                    data: {
                                        lat: that.data.recieverInfo.lat,
                                        lng: that.data.recieverInfo.lng
                                    },
                                    success: res => {
                                        if (res.data) {
                                            that.setData({
                                                delivery_price: res.extra.delivery_price,
                                                isDelivery: true
                                            });
                                        } else {
                                            that.setData({
                                                delivery_price: 0,
                                                isDelivery: false
                                            });
                                        }
                                        resolve();
                                    }
                                });
                            }
                        } else {
                            that.setData({
                                delivery_price: 0,
                                isDelivery: false,
                                isDeliveryTip: res.message
                            });
                            resolve();
                        }
                    },
                    fail(res) {
                        that.setData({
                            delivery_price: 0,
                            isDelivery: false,
                            isDeliveryTip: res.message
                        });
                    }
                });
            });
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarTitle({
                    title: res.extra.title
                });
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    apptitle: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    leader_express: res.extra.l_express,
                    rp_name: res.extra.rp_name,
                    order_start: res.extra.order_start,
                    order_start_switch: res.extra.order_start_switch,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    ["goodsListStyle.leaderName"]: res.extra.leader_title ? res.extra.leader_title : "团长",
                    communityName: res.extra.community_title ? res.extra.community_title : "社区",
                    leader_address_on: res.extra.leader_address_on,
                    integral_status: res.extra.integral_status,
                    leader_weight: res.extra.leader_weight,
                    plat_weight: res.extra.plat_weight,
                    is_plat_weight: res.extra.is_plat_weight,
                    is_leader_weight: res.extra.is_leader_weight,
                    basic_pack: res.extra.basic_pack,
                    is_basic_pack: res.extra.is_basic_pack,
                    // delivery_time:res.extra.delivery_range.delivery_time,
                    delivery_time_on: res.extra.delivery_range.delivery_time_on,
                    delivery_type: res.extra.delivery_type
                });
                if (that.data.delivery_time_on == 1) {
                    var delivery_range = res.extra.delivery_range;
                    var delivery_rangeArr = [ delivery_range.delivery_day, delivery_range.delivery_time ];
                    that.setData({
                        delivery_rangeArr: delivery_rangeArr,
                        delivery_time_on: 1
                    });
                }
                //处理模块开关
                                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    features: features
                });
                //设置模块颜色
                                var componentStyle = that.data.componentStyle;
                that.setData({
                    componentStyle: {
                        ...componentStyle,
                        color_main: !res.extra.color_main ? "#FE513B" : res.extra.color_main,
                        color_minor: !res.extra.color_minor ? "#FE513B" : res.extra.color_minor
                    }
                });
                this.getRecieverInfo().then(res => {
                    // this.getRecieverAddress().then(res => {
                    console.log("delivery_price" + this.data.delivery_price);
                    this.getExpressInfo();
                    // });
                                });
            }
        });
    },
    bindMultiPickerChange: function(e) {
        var delivery_rangeArr = this.data.delivery_rangeArr;
        this.setData({
            multiIndex: e.detail.value
        });
        var multiIndex = this.data.multiIndex;
        var reach_time = delivery_rangeArr[0][multiIndex[0]] + " " + delivery_rangeArr[1][multiIndex[1]];
        var date_rang_time = new Date(reach_time + ":00").getTime();
        var now_date = new Date().getTime();
        if (date_rang_time < now_date) {
            wx.showToast({
                icon: "none",
                title: "选择时间必须大于当前时间"
            });
            return false;
        } else {
            this.setData({
                reach_time: reach_time
            });
        }
    },
    bindMultiPickerColumnChange(e) {
        var current = e.detail.value;
        var multiIndex = this.data.multiIndex;
        multiIndex = [ multiIndex[0], current ];
        var delivery_rangeArr = this.data.delivery_rangeArr;
        var reach_time = delivery_rangeArr[0][multiIndex[0]] + " " + delivery_rangeArr[1][multiIndex[1]];
        var date_rang_time = new Date(reach_time + ":00").getTime();
        var now_date = new Date().getTime();
        if (date_rang_time < now_date) {
            wx.showToast({
                icon: "none",
                title: "选择时间必须大于当前时间"
            });
            return false;
        } else {
            this.setData({
                multiIndex: multiIndex,
                reach_time: reach_time
            });
        }
    },
    //团长切换
    leader_change: function(e) {
        var address = e.currentTarget.dataset.address;
        var is_leader = wx.getStorageSync("my_leader").is_leader;
        if (is_leader == 1) {
            wx.showModal({
                title: "提示",
                content: "您自己是" + that.data.leaderName + "不能切换" + that.data.leaderName + "！"
            });
        }
        if (this.data.leader_change == 1 && is_leader != 1) {
            wx.navigateTo({
                url: "/pages/nearby_group2/nearby_group2"
            });
        }
    },
    getCloseOrder: function() {
        var that = this;
        common.request({
            endpoint: "Order/orderinfo/close_order",
            method: "post",
            success: res => {
                console.log(res);
                that.setData({
                    close_order: res.extra.close_order
                });
            }
        });
    },
    choose: function() {
        var choose = this.data.choose;
        if (choose == 1) {
            choose = 2;
        } else {
            choose = 1;
        }
        this.setData({
            choose: choose
        });
    },
    index_call: function(e) {
        var phone = e.currentTarget.dataset.phone;
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    /** 
   * 开始下单
   */
    prePayOrder: function(e) {
        var that = this;
        if (!that.data.isPayStatus) {
            //满减条件未达成
            return false;
        }
        var status = that.data.status;
        var cart_storage = wx.getStorageSync("cart");
        var name = e.detail.value.name;
        var phone = e.detail.value.phone;
        var house_number = e.detail.value.house_number;
        var remark = e.detail.value.remark;
        let form_id = e.detail.formId;
        var group = that.data.group;
        let leader_id = that.data.myleaderinfo.leader_id;
        console.log(that.data.items);
        var formValue = e.detail.value;
        var formConfig = that.data.formConfig;
        if (formConfig.length > 0) {
            for (var i = 0; i < formConfig.length; i++) {
                //处理数组
                if (formValue[formConfig[i].formData.name] instanceof Array) {
                    formValue[formConfig[i].formData.name] = formValue[formConfig[i].formData.name].join("-");
                }
                if (formConfig[i].formType == 4) {
                    formValue[formConfig[i].formData.name] = formValue[formConfig[i].formData.name] ? 1 : 0;
                }
                //找出必填项
                                var important = formConfig[i].formData.important == true ? true : false;
                //console.log(important, formConfig[i].formData.important)
                                if (important) {
                    //判断有没有值
                    var formItemValue = formValue[formConfig[i].formData.name];
                    console.log(formItemValue);
                    if (!formItemValue || formItemValue.length == 0) {
                        //没有值
                        wx.showToast({
                            icon: "none",
                            title: formConfig[i].formData.title + "不能为空"
                        });
                        return false;
                    } else {
                        if (formConfig[i].formData.name == "phone") {
                            var reg2 = /^[1][0-9][0-9]{9}$/;
                            if (!reg2.test(e.detail.value.phone)) {
                                wx.showModal({
                                    title: "提示",
                                    content: "请输入正确的手机号码！",
                                    showCancel: false
                                });
                                return false;
                            }
                        }
                    }
                }
            }
        }
        that.setData({
            payment_status: 0,
            buy_info: e.detail.value,
            form_id: form_id
        });
        that.filterTeamer();
    },
    // confirmInfo(e) {
    //   var that = this;
    //   that.setData({
    //     form_id: e.detail.formIdArry
    //   })
    //   console.log(e.detail.formIdArry, "xixixi")
    //   var payButtonDisabled = that.data.payButtonDisabled;
    //   if (!this.data.isPayStatus || payButtonDisabled) {
    //     //不满足满减条件或按钮禁用
    //     return false;
    //   }
    //   that.setData({
    //     payButtonDisabled: true //禁用支付按钮
    //   })
    //验证收件人信息
    //   var recieverInfo = that.data.recieverInfo;
    //   if (!recieverInfo.receiverName) {
    //     wx.showModal({
    //       title: '您还没有收件人',
    //       content: '是否去选择收件人',
    //       success(res) {
    //         if (res.confirm) {
    //           that.setData({
    //             payButtonDisabled: false //启用支付按钮
    //           })
    //           wx.navigateTo({
    //             url: '/addressManagerPackage/pages/addressList/addressList',
    //           })
    //         } else if (res.cancel) {
    //           that.setData({
    //             payButtonDisabled: false //启用支付按钮
    //           })
    //         }
    //       }
    //     })
    //     return false;
    //   }
    //   // var status = that.data.status;
    //   // var cart_storage = wx.getStorageSync('cart')
    //   // var name = e.detail.value.name;
    //   // var phone = e.detail.value.phone;
    //   // var house_number = e.detail.value.house_number;
    //   // var remark = e.detail.value.remark
    //   //let form_id = that.data.form_id;
    //   // var group = that.data.group;
    //   // let leader_id = that.data.myleaderinfo.leader_id
    //   // console.log(that.data.items)
    //   that.setData({
    //     payment_status: 0,
    //     //form_id: form_id,
    //   })
    //   that.filterTeamer();
    // },
    confirmInfo: function() {
        let that = this;
        if (!that.data.recieverInfo.area && that.data.choose_type != 1 || !that.data.recieverInfo.area && that.data.expressPro.item.length) {
            wx.showModal({
                title: "提示",
                content: "暂无地址信息,请先选择地址！",
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: "/addressManagerPackage/pages/addressList/addressList"
                        });
                    }
                }
            });
            return false;
        }
        if (!that.data.reach_time && that.data.choose_type == 2 && that.data.delivery_time_on == 1) {
            wx.showModal({
                title: "提示",
                content: "请选择送达时间!",
                success(res) {}
            });
            return false;
        }
        //let totalTem = that.data.platPro.item.length + that.data.expressPro.item.length;
        // that.getDatashow(); //开始上传时间次数
                if (that.data.subscribeMessage) {
            // for (var i = 0; i < totalTem.length-1; i++) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {
                    //that.getDatashow(); //开始上传时间次数
                },
                fail(err) {
                    console.log(err);
                },
                complete() {
                    that.confirmInfo_ch();
                }
            });
            // }
                } else {
            that.confirmInfo_ch();
        }
    },
    getDatashow() {
        let that = this;
        let message_times = that.data.platPro.item.length + that.data.expressPro.item.length;
        common.request({
            endpoint: "Member/member/message_times",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid,
                message_times: message_times
            },
            success: res => {}
        });
    },
    confirmInfo_ch() {
        var that = this;
        var payButtonDisabled = that.data.payButtonDisabled;
        if (!this.data.isPayStatus || payButtonDisabled) {
            //不满足满减条件或按钮禁用
            return false;
        }
        that.setData({
            payButtonDisabled: true
        });
        //验证收件人信息
                var recieverInfo = that.data.recieverInfo;
        if (!recieverInfo.receiverName) {
            wx.showModal({
                title: "提示",
                content: "请选择收件人",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            payButtonDisabled: false
                        });
                    }
                }
            });
            return false;
        }
        if (!/^1[23456789]\d{9}$/.test(recieverInfo.phone) && that.data.choose_type == 1) {
            wx.showModal({
                title: "提示",
                content: "请输入正确的手机号码！",
                showCancel: false,
                success(res) {
                    if (res.confirm) {
                        that.setData({
                            payButtonDisabled: false
                        });
                    }
                }
            });
            return false;
        }
        // var status = that.data.status;
        // var cart_storage = wx.getStorageSync('cart')
        // var name = e.detail.value.name;
        // var phone = e.detail.value.phone;
        // var house_number = e.detail.value.house_number;
        // var remark = e.detail.value.remark
        //let form_id = that.data.form_id;
        // var group = that.data.group;
        // let leader_id = that.data.myleaderinfo.leader_id
        // console.log(that.data.items)
                that.setData({
            payment_status: 0
        });
        that.filterTeamer();
    },
    /** 
   * 记录 input 的值
   * e: object 
   */
    recordValue: function(e) {
        let key = e.currentTarget.dataset.name;
        let value = e.detail.value;
        console.log(key);
        this.setData({
            [key]: value
        });
    },
    /**
   * 记录收件人修改
   */
    recordValue_info: function(e) {
        let that = this;
        let key = "recieverInfo." + e.detail.key;
        let value = e.detail.value;
        that.setData({
            [key]: value
        });
    },
    /** 
   * 重平衡价格
   */
    reBlancePrice: function() {
        var that = this;
        if (that.data.deliver_method == "self") {
            console.log(that.data.all_price);
            that.setData({
                totale_price: parseFloat(that.data.discounted_price).toFixed(2),
                totale_price2: parseFloat(that.data.all_price).toFixed(2),
                click_time: 0
            });
            //判断余额
                        that.balanceIsOpen(parseFloat(that.data.discounted_price).toFixed(2));
        } else if (that.data.deliver_method == "leader") {
            var yunfei = that.data.yunfei;
            let click_time = that.data.click_time;
            var totale_price = parseFloat(that.data.discounted_price) + parseFloat(yunfei);
            that.setData({
                totale_price: totale_price.toFixed(2),
                totale_price2: parseFloat(that.data.all_price).toFixed(2),
                click_time: 1
            });
            //判断余额
                        that.balanceIsOpen(totale_price.toFixed(2));
        }
    },
    /** 
   * 选择运送方式
   */
    selectDeliverMethod: function(e) {
        let method = e.currentTarget.dataset.value;
        this.setData({
            deliver_method: method
        });
        this.reBlancePrice();
    },
    //获取下单商品
    getGoods: function() {
        var that = this;
        var arr_id = that.data.arr_id;
        var count_id = that.data.count_id;
        var time_id = that.data.time_id;
        var items = that.data.items;
        var refund = that.data.refund;
        var params = {
            sku_id: items,
            time_id: time_id
        };
        if (that.data.group_id) {
            params["group_id"] = that.data.group_id;
        }
        common.request({
            endpoint: "Order/orderinfo/product_info",
            method: "post",
            data: params,
            success: res => {
                var order_goods = res.extra.default.concat(res.extra.express);
                // if (that.data.newUserProductPrice) {
                //   //如果是新人专享，将传过来的价格赋值给price
                //   order_goods[0].price = that.data.newUserProductPrice
                // }
                                var goods = that.data.goods;
                var all_price = 0;
                var all_price3 = 0;
                //计算除去快递后的会员总价
                                var no_refundGood = that.data.no_refundGood;
                var refundProPrice = 0;
                //满减商品总价
                                var spec_fund = 0;
                //判断是否存在专项资金购买（普通和专项存在也有专项资金标识，无法购买，只能提示）
                                var isSpec_fund = 1;
                //判断是否可以专项资金购买
                                var total_mem_level_discount = 0;
                //总折扣优惠
                                var total_weight = 0;
                //重量
                                var product_packing_fee = 0;
                //商品包装费
                                for (var j = 0; j < order_goods.length; j++) {
                    if (order_goods[j].money_refund == 0) {
                        no_refundGood++;
                    } else {
                        //计算满减商品总价
                        if (order_goods[j].is_vip == 1 && that.data.features.memberVip == 1 && that.data.vipStatus == 1) {
                            refundProPrice += parseFloat(order_goods[j].vip_price) * parseFloat(goods[j][1]);
                        } else {
                            refundProPrice += parseFloat(order_goods[j].price) * parseFloat(goods[j][1]);
                        }
                    }
                    if (order_goods[j].spec_fund == 1) {
                        spec_fund = 1;
                    }
                    if (order_goods[j].spec_fund == 0) {
                        isSpec_fund = 0;
                    }
                }
                //计算商品的总金额***********
                                for (var i = 0; i < order_goods.length; i++) {
                    if (order_goods[i].only_express == 0) {
                        if (order_goods[i].is_vip == 1 && that.data.features.memberVip == 1 && that.data.vipStatus == 1) {
                            all_price3 += parseFloat(order_goods[i].vip_price) * parseFloat(goods[i][1]);
                        } else if (order_goods[i].is_mem_level == 1) {
                            all_price3 += parseFloat(order_goods[i].mem_level_price) * parseFloat(goods[i][1]);
                        } else {
                            all_price3 += parseFloat(order_goods[i].price) * parseFloat(goods[i][1]);
                        }
                        total_weight += parseFloat(order_goods[i].weight) * parseFloat(goods[i][1]);
                    }
                    //商品包装费
                                        product_packing_fee += parseFloat(order_goods[i].packing_fee) * parseFloat(goods[i][1]);
                    if (order_goods[i].is_vip == 1 && that.data.features.memberVip == 1 && that.data.vipStatus == 1) {
                        all_price += parseFloat(order_goods[i].vip_price) * parseFloat(goods[i][1]);
                        total_mem_level_discount = total_mem_level_discount + parseFloat(order_goods[i].price - order_goods[i].vip_price) * parseFloat(goods[i][1]);
                    } else if (order_goods[i].is_mem_level == 1) {
                        all_price += parseFloat(order_goods[i].mem_level_price) * parseFloat(goods[i][1]);
                        total_mem_level_discount = total_mem_level_discount + parseFloat(order_goods[i].price - order_goods[i].mem_level_price) * parseFloat(goods[i][1]);
                    } else {
                        all_price += parseFloat(order_goods[i].price) * parseFloat(goods[i][1]);
                    }
                    if (order_goods[i].status == 1) {
                        if (parseInt(goods[i][1]) > parseInt(order_goods[i].stock_number)) {
                            wx.showModal({
                                title: "提示",
                                content: order_goods[i].name + "库存不足",
                                showCancel: false,
                                success: function(res) {
                                    if (res.confirm) {
                                        wx.navigateBack();
                                    }
                                }
                            });
                        }
                    } else {
                        wx.showModal({
                            title: "提示",
                            content: order_goods[i].name + "已下架",
                            showCancel: false,
                            success: function(res) {
                                wx.navigateBack();
                            }
                        });
                    }
                }
                that.setData({
                    total_mem_level_discount: total_mem_level_discount.toFixed(2)
                });
                let all_price2 = all_price;
                //商品总额，预计减去满减，减去积分，减去红包，计算最终支付金额
                                if (refund.refund_has != "") {
                    all_price2 = parseFloat(all_price) - parseFloat(refund.refund_has.refund_limit) - parseFloat(that.data.total_discount);
                    if (all_price2 <= 0) {
                        all_price2 = .01;
                    }
                }
                var listData = that.orderList(order_goods);
                //全部商品
                                var goodsListData = {
                    item: listData.platPro.concat(listData.expressPro)
                };
                //非快递商品
                                var platPro = {
                    item: listData.platPro
                };
                //仅快递商品
                                var expressPro = {
                    item: listData.expressPro
                };
                //计算平台商品
                                that.platCountInfo(platPro.item);
                //计算快递商品运费
                                var payExpressCost = that.expressCountInfo(expressPro.item);
                all_price2 += payExpressCost;
                // if (refund.status == 1 && parseFloat(all_price) >= refund.refund_has.refund_barrier) {
                //   all_price2 = parseFloat(all_price) - parseFloat(refund.refund_limit)
                //   console.log(parseFloat(all_price)- parseFloat(refund.refund_limit))
                //   if (all_price2 <= 0) {
                //     all_price2 = 0.01
                //   }
                // 
                                that.setData({
                    all_price2: parseFloat(all_price2).toFixed(2),
                    all_price: parseFloat(all_price).toFixed(2),
                    all_price3: parseFloat(all_price3).toFixed(2),
                    totale_price: parseFloat(all_price2).toFixed(2),
                    total_weight: total_weight,
                    product_packing_fee: product_packing_fee,
                    order_goods: order_goods,
                    no_refundGood: no_refundGood,
                    spec_fund: spec_fund,
                    isSpec_fund: isSpec_fund,
                    goodsListData: goodsListData,
                    refundProPrice: refundProPrice,
                    platPro: platPro,
                    expressPro: expressPro
                });
                // setTimeout(()=>{
                // },3000)
                                that.startBuyCondition(that.data.all_price);
                //判断起购条件
                                that.getDiscount();
                //商品价格减去积分和满减之后，>0.01默认可以使用红包
                        },
            fail(res) {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    showCancel: false,
                    success: function() {
                        wx.navigateBack();
                    }
                });
            }
        });
    },
    orderList(data) {
        let that = this;
        var goods = that.data.goods;
        var items = that.data.items;
        if (data || data.length > 0) {
            var platPro = [];
            var expressPro = [];
            data.forEach((proInfo, proIndx) => {
                var pro = {
                    id: proInfo.id,
                    //订单id，
                    proId: proInfo.pro_id,
                    //商品id
                    icon: proInfo.icon,
                    //商品缩略图
                    proName: proInfo.name,
                    //商品名称
                    spec: proInfo.sku_arrtibutes,
                    //规格
                    money_refund: proInfo.money_refund,
                    //是否是满减商品
                    spec_fund: proInfo.spec_fund,
                    price: proInfo.price,
                    //商品单价
                    num: goods[proIndx][1],
                    //数量
                    status: proInfo.status,
                    //售后状态，-1——仅退款，-2—— 退货退款，-3退货换货
                    order_status: proInfo.order_status,
                    //订单状态
                    vip_price: proInfo.vip_price,
                    //会员价格
                    is_vip: proInfo.is_vip,
                    is_mem_level: proInfo.is_mem_level,
                    mem_level_price: proInfo.mem_level_price,
                    supplier_type: proInfo.supplier_type,
                    weight: proInfo.weight
                };
                if (items[proIndx].proType == 0) {
                    platPro.push(pro);
                } else {
                    expressPro.push(pro);
                }
            });
            return {
                platPro: platPro,
                expressPro: expressPro
            };
        }
    },
    getItems: function(item) {
        if (!item) {
            return [];
        }
        return item.split("|").map(value => {
            let a = value.split(",");
            let t = {
                sku_id: a[0] || 0,
                num: a[1] || 0,
                credit_sent: a[2] || 0,
                proType: a[3]
            };
            return t;
        });
    },
    getInfo: function(type) {
        var openid = wx.getStorageSync("user").openid;
        var that = this;
        common.request({
            endpoint: "member/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                console.log(res);
                var formConfig = that.data.formConfig;
                if (type == 1) {
                    formConfig.forEach((item, index) => {
                        switch (item.formData.name) {
                          case "name":
                            if (res.extra.name) {
                                item.formData.value = res.extra.name;
                            } else {
                                item.formData.value = "";
                            }
                            break;

                          case "phone":
                            if (res.extra.name) {
                                item.formData.value = res.extra.phone;
                            } else {
                                item.formData.value = "";
                            }
                            break;

                          case "city":
                            if (res.extra.name) {
                                item.formData.value = res.extra.address_name;
                            } else {
                                item.formData.value = [];
                            }
                            break;

                          case "house_number":
                            if (res.extra.name) {
                                item.formData.value = res.extra.address_other;
                            } else {
                                item.formData.value = "";
                            }
                            break;
                        }
                    });
                }
                that.setData({
                    name: res.extra.name,
                    phone: res.extra.phone,
                    house_number: res.extra.address_other,
                    remark: res.extra.remark,
                    formConfig: formConfig,
                    myInfo: res.extra
                });
            }
        });
    },
    /**
   * 取消后，按钮点击跳转设置
   */
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {
                console.log(res);
            }
        });
        wx.openSetting({
            success(res) {
                console.log(res);
                if (res.authSetting["scope.userInfo"]) {
                    that.getUserInfo();
                }
                if (that.data.warrant || res.authSetting["scope.userInfo"]) {
                    that.setData({
                        showInfoTip: false
                    });
                }
            }
        });
    },
    remind: function() {
        if (!this.data.isPayStatus) {
            //起购价打开，不满足起购条件
            return false;
        }
        wx.showModal({
            title: "提示",
            content: "请在订单列表页继续支付！",
            success: function() {
                wx.switchTab({
                    url: "/pages/order/order"
                });
            }
        });
    },
    close_confirm: function() {
        this.setData({
            confirm_lead: 0,
            payment_status: 1,
            payButtonDisabled: false
        });
    },
    confirm_order: function(e) {
        console.log(e, "submit");
        var that = this;
        // var form_id = that.data.form_id;
        //var buy_info = that.data.buy_info;
                var recieverInfo = that.data.recieverInfo;
        var remark = that.data.remark;
        let leader_id = that.data.myleaderinfo ? that.data.myleaderinfo.leader_id : "";
        var cart_storage = wx.getStorageSync("cart");
        var status = that.data.status;
        var reach_time = that.data.reach_time;
        var cart = [];
        var cart_count = "";
        var discount_id = that.data.discount_id;
        var choose_type = that.data.choose_type;
        var delivery_channel = "";
        var time_id = that.data.time_id;
        if (choose_type == 0) {
            delivery_channel = "leader";
        } else if (choose_type == 1) {
            delivery_channel = "self";
        } else {
            delivery_channel = "seller";
        }
        that.setData({
            confirm_lead: 0
        });
        var radioIndex = 0;
        var payWayList = that.data.payWayList;
        payWayList.forEach((item, index) => {
            if (item.isChecked) {
                if (item.payWayName == "余额") {
                    radioIndex = 1;
                } else if (item.payWayName == "微信支付") {
                    radioIndex = 0;
                } else {
                    radioIndex = 2;
                }
            }
        });
        //调整配送方式码
                var choose_type2;
        if (choose_type == 1) {
            choose_type2 = 1;
        } else if (choose_type == 0) {
            choose_type2 = 2;
        } else if (choose_type == 2) {
            choose_type2 = 3;
        }
        console.log(choose_type2, "choose_type2");
        //合并商品
                var platPro = that.data.platPro;
        var expressPro = that.data.expressPro;
        platPro.item.forEach((item, index) => {
            item.delivery_channel = choose_type2;
        });
        expressPro.item.forEach((item, index) => {
            item.delivery_channel = 4;
        });
        var pro = platPro.item.concat(expressPro.item);
        var items = that.data.items;
        //
                items.forEach((item, index) => {
            item.delivery_channel = pro[index].delivery_channel;
            item.supplier_type = pro[index].supplier_type;
        });
        wx.showLoading({
            title: "订单支付中..."
        });
        common.request({
            endpoint: "Order/common/prepay-order",
            method: "post",
            data: {
                name: recieverInfo.receiverName,
                //姓名
                phone: recieverInfo.phone,
                //电话号码
                house_number: recieverInfo.area,
                //地址
                address_name: recieverInfo.city ? recieverInfo.city.replace(/-/g, ",") : "",
                //所在地区
                items: items,
                //商品
                remark: remark,
                //备注
                leader_id: leader_id,
                //团长id
                delivery_channel: delivery_channel,
                //配送方式
                // form_id: form_id,
                voucher: discount_id,
                //红包id
                seckill_session: time_id,
                //方式
                balance_status: radioIndex,
                integral_status: that.data.integral_check,
                group_solit_id: that.data.group_id,
                reach_time: reach_time,
                lng: recieverInfo.lng ? recieverInfo.lng + "" : "",
                lat: recieverInfo.lat ? recieverInfo.lat + "" : ""
            },
            success: res => {
                wx.hideLoading();
                console.log(res, "下单成功");
                if (status == 1) {
                    for (var i = 0; i < cart_storage.length; i++) {
                        if (cart_storage[i]["select"] == 0) {
                            cart.push(cart_storage[i]);
                            cart_count += cart_storage[i]["count"];
                        }
                    }
                    wx.setStorage({
                        key: "cart",
                        data: cart
                    });
                    wx.setStorage({
                        key: "cart_count",
                        data: cart_count
                    });
                }
                console.log("下单成功");
                var order_no = res.order_no;
                that.setData({
                    order_no: order_no
                });
                //支付方式选择
                                that.payWay(res, order_no);
            },
            fail: err => {
                wx.hideLoading();
                if (err.code == 8) {
                    $Toast({
                        content: err.message,
                        success() {
                            wx.navigateBack();
                        }
                    });
                } else {
                    if (err.message == "未达到订单起购价") {
                        $Toast({
                            content: "满￥" + that.data.order_start + "元才可下单",
                            success() {
                                wx.navigateBack();
                            }
                        });
                        setTimeout(function() {
                            wx.navigateBack();
                        }, 2e3);
                    } else if (err.code == 5) {
                        wx.showModal({
                            title: "提示",
                            content: err.message,
                            success: res => {
                                wx.navigateBack();
                            }
                        });
                    } else {
                        wx.showModal({
                            title: "提示",
                            content: err.message,
                            success: res => {
                                wx.navigateBack();
                            }
                        });
                    }
                }
            }
        });
    },
    confirm_balance() {
        var that = this;
        let balance_status;
        that.data.payWayList.forEach((item, index) => {
            if (item.payWayName == "余额" && item.isChecked) {
                balance_status = 1;
            } else if (item.payWayName == "专项资金" && item.isChecked) {
                balance_status = 2;
            }
        });
        var order_no = that.data.order_no;
        common.request({
            endpoint: "Order/common/sync-notify",
            method: "post",
            data: {
                order_no: order_no,
                balance_status: balance_status
            },
            success: res => {
                that.setData({
                    balance_confirm: 0
                });
                setTimeout(function() {
                    wx.reLaunch({
                        url: "/pages/order_confirm/order_confirm?order_no=" + order_no
                    });
                }, 500);
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message
                });
            }
        });
    },
    close_balance_confirm() {
        this.setData({
            balance_confirm: 0
        });
        wx.switchTab({
            url: "/pages/order/order",
            success: function(e) {
                let page = getCurrentPages().pop();
                if (page == undefined || page == null) return;
                page.onLoad();
            }
        });
    },
    choose_label: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        that.setData({
            discount_label: id
        });
    },
    close_discount: function() {
        this.setData({
            discount_alert: 0
        });
    },
    show_discount: function() {
        var that = this;
        that.setData({
            discount_alert: 1
        });
    },
    //选择红包
    choose_discount: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        var choose_discount = that.data.choose_discount;
        var discount_price = e.currentTarget.dataset.price;
        var all_price = that.data.all_price;
        var all_price2 = that.data.all_price2;
        var title = e.currentTarget.dataset.title;
        var discount_use = that.data.discount_use;
        var confirm_time = that.data.confirm_time;
        var deliver_method = that.data.deliver_method;
        var choose_type = that.data.choose_type;
        var yunfei = that.data.yunfei;
        var rp_name = that.data.rp_name;
        if (choose_type == 0 || choose_type == 2) {
            that.setData({
                click_time: 0
            });
        }
        console.log(all_price2 + "dddd");
        if (choose_discount == id) {
            that.setData({
                choose_discount: -1,
                discount_id: 0,
                discount_price: 0,
                discount_price2: 0,
                totale_price: parseFloat(all_price2).toFixed(2),
                discount_title: discount_use + "个" + rp_name + "可选"
            });
            //判断余额
                        console.log(parseFloat(all_price2).toFixed(2), "4");
            that.balanceIsOpen(parseFloat(all_price2).toFixed(2));
        } else {
            that.setData({
                choose_discount: id,
                discount_price: discount_price,
                totale_price: parseFloat(all_price2).toFixed(2),
                discount_id: id,
                discount_title: title,
                discount_price2: discount_price
            });
            //判断余额
                        console.log(parseFloat(all_price2).toFixed(2), "5");
            that.balanceIsOpen(parseFloat(all_price2).toFixed(2));
            if (confirm_time != 0) {
                that.setData({
                    discount_id2: id,
                    confirm_time: confirm_time
                });
            }
            confirm_time++;
        }
    },
    //优惠券信息
    getDiscount: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var time_id = that.data.time_id;
        var group_id = that.data.group_id;
        common.request({
            endpoint: "Order/voucherinfo/voucher-condition",
            method: "post",
            data: {
                openid: openid,
                items: that.data.items,
                time_id: time_id,
                group_id: group_id
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                that.setData({
                    discount_title: res.extra.available ? res.extra.available : "0" + "个红包可选",
                    discount: res.extra.voucher,
                    discount_use: res.extra.available,
                    discount_unuse: res.extra.unavailable
                });
                if (that.data.discount_use > 0 && that.data.all_price2 > .01) {
                    //使用红包
                    var discount = that.data.discount;
                    discount = discount.filter(x => {
                        return x.flag == 1;
                    });
                    var all_price2 = that.data.all_price2;
                    all_price2 = parseFloat(all_price2) - parseFloat(discount[0].discount);
                    if (all_price2 <= 0) {
                        all_price2 = .01;
                    }
                    that.setData({
                        choose_discount: discount[0].id,
                        discount_price: discount[0].discount,
                        all_price2: parseFloat(all_price2).toFixed(2),
                        totale_price: parseFloat(all_price2).toFixed(2),
                        discount_id: discount[0].id,
                        discount_title: discount[0].title,
                        discount_price2: discount[0].discount
                    });
                } else {
                    that.setData({
                        choose_discount: 0,
                        discount_price: 0,
                        discount_id: 0,
                        discount_price2: 0
                    });
                }
                that.getMyLeaderInfo(that.data.all_price3);
                //我的团长信息
                        }
        });
    },
    confirm_discount: function() {
        var that = this;
        var discount_price2 = that.data.discount_price2;
        var refund_money = that.data.refund_money;
        var discount_id = that.data.discount_id;
        let discounted_price = that.data.discounted_price;
        var discount_id2 = that.data.discount_id2;
        var discount_price = that.data.discount_price;
        //红包金额
                var totale_price = that.data.totale_price;
        console.log("discount_id:" + discount_id);
        console.log("discount_id2:" + discount_id2);
        var choose_type = that.data.choose_type;
        var other_money = that.data.other_money;
        var yunfei = that.data.yunfei;
        var all_price = that.data.all_price2;
        var express = that.data.express;
        var trans_for_free_barrier = that.data.trans_for_free_barrier;
        var on_off_trans_free = that.data.on_off_trans_free;
        let good_money = 0;
        // if(discount_id==discount_id2){
                console.log(discount_price);
        good_money = parseFloat(that.data.all_price) - parseFloat(discount_price) - parseFloat(refund_money);
        //商品总价减去满减减去积分兑换
                if (that.data.integral_status == 1 && that.data.integral_check == 1) {
            good_money = parseFloat(good_money) - parseFloat(that.data.total_discount);
        }
        var all_price = that.data.all_price;
        if (good_money <= 0) {
            good_money = .01;
        }
        // }
                var difference = parseFloat(trans_for_free_barrier) - parseFloat(all_price);
        if (choose_type == 2 && on_off_trans_free == 1) {
            other_money = express;
            if (difference <= 0) {
                other_money = 0;
            }
        }
        let payExpressCost = that.data.payExpressCost;
        let total_packing_fee = that.data.total_packing_fee;
        totale_price = parseFloat(other_money) + parseFloat(good_money) + parseFloat(payExpressCost) + parseFloat(total_packing_fee);
        // let preference = parseFloat(discount_price2) + parseFloat(refund_money)+parseFloat(that.data.total_mem_level_discount)
                let preference = parseFloat(discount_price2) + parseFloat(refund_money);
        if (that.data.integral_status == 1 && that.data.integral_check == 1) {
            preference = parseFloat(preference) + parseFloat(that.data.total_discount);
        }
        that.setData({
            totale_price: parseFloat(totale_price).toFixed(2),
            discount_alert: 0,
            other_money: other_money,
            difference: difference.toFixed(2),
            preference: preference.toFixed(2)
        });
        //判断余额
                console.log(totale_price.toFixed(2), "6");
        that.balanceIsOpen(totale_price.toFixed(2));
    },
    //切换配送方式、重算支付金额
    chooseMethod: function(e) {
        var that = this;
        var discount_price2 = that.data.discount_price2;
        var refund_money = that.data.refund_money;
        var total_integral = that.data.total_integral;
        let preference = parseFloat(discount_price2) + parseFloat(refund_money) + parseFloat(that.data.total_mem_level_discount);
        var money = e.currentTarget.dataset.money;
        var type = e.currentTarget.dataset.type;
        var all_price = that.data.all_price;
        var all_price2 = that.data.all_price2;
        var discount_price = that.data.discount_price;
        var express = that.data.express;
        var trans_for_free_barrier = that.data.trans_for_free_barrier;
        var on_off_trans_free = that.data.on_off_trans_free;
        let good_money = parseFloat(all_price) - parseFloat(discount_price) - parseFloat(that.data.refund_money);
        if (that.data.integral_status == 1 && that.data.integral_check == 1) {
            good_money = parseFloat(good_money) - parseFloat(that.data.total_discount);
        }
        if (good_money <= 0) {
            good_money = .01;
        }
        var all_price = that.data.all_price;
        let difference = parseFloat(trans_for_free_barrier) - parseFloat(that.data.all_price3);
        var platWay;
        switch (type) {
          case "0":
            platWay = 2;
            //团长配送
                        break;

          case "1":
            platWay = 1;
            //到点自提
                        break;

          case "2":
            platWay = 3;
            //平台配送
                        break;

          default:
            platWay = "";
        }
        //先计算是否超过包装费
                if (platWay == 2 && that.data.is_leader_weight == 1) {
            //团长
            var total_weight = that.data.total_weight * 1e3;
            var leader_weight = that.data.leader_weight;
            if (total_weight > leader_weight) {
                var weightTip = "*重量：" + total_weight + "g" + " 超出配送限制(" + leader_weight + "g)无法支付";
                this.setData({
                    payButtonDisabled: true,
                    weightTipShow: 1,
                    weightTip: weightTip
                });
            }
        } else if (platWay == 3 && that.data.is_plat_weight == 1) {
            //平台
            var total_weight = that.data.total_weight * 1e3;
            var plat_weight = that.data.plat_weight;
            if (total_weight > plat_weight) {
                var weightTip = "*重量：" + total_weight + "g" + " 超出配送限制(" + plat_weight + "g)无法支付";
                this.setData({
                    payButtonDisabled: true,
                    weightTipShow: 1,
                    weightTip: weightTip
                });
            }
        } else {
            if (type == 2) {
                if (on_off_trans_free == 1 && difference <= 0) {
                    money = 0;
                    that.setData({
                        payButtonDisabled: false,
                        defferNum: "立即支付"
                    });
                } else if (that.data.delivery_type == 2) {
                    if (!that.data.isDelivery) {
                        that.setData({
                            payButtonDisabled: true,
                            defferNum: that.data.isDeliveryTip
                        });
                    } else {
                        that.setData({
                            payButtonDisabled: false,
                            defferNum: "立即支付"
                        });
                    }
                    money = that.data.delivery_price;
                }
            } else {
                this.setData({
                    payButtonDisabled: false,
                    weightTipShow: 0
                });
            }
        }
        console.log("切换配送方式");
        console.log(type);
        if (type == 0 && that.data.pinkage == 1 && parseFloat(that.data.all_price3) >= parseFloat(that.data.pinkage_price) || type == 0 && that.data.vipLeaderExpress == 1) {
            console.log("切换后满足团长免配送费");
            money = 0;
        }
        var payExpressCost = that.data.payExpressCost;
        let totale_price = parseFloat(good_money) + parseFloat(money) + parseFloat(payExpressCost) + parseFloat(that.data.total_packing_fee);
        if (that.data.integral_status == 1 && that.data.integral_check == 1) {
            preference = parseFloat(preference) + parseFloat(that.data.total_discount);
        }
        that.setData({
            totale_price: totale_price.toFixed(2),
            choose_type: type,
            platWay: platWay,
            other_money: money,
            difference: difference.toFixed(2),
            preference: preference.toFixed(2)
        });
        //设置收货人信息
        //that.setRecieverInfo(type);
        //判断余额
                that.balanceIsOpen(totale_price.toFixed(2));
        wx.showToast({
            title: "配送金额变化",
            icon: "none",
            duration: 800
        });
    },
    //秒杀是否启用红包
    getKilldis: function() {
        var that = this;
        var time_id = that.data.time_id;
        common.request({
            endpoint: "set/seckill_envelope_isopen",
            method: "post",
            data: {
                time_id: time_id
            },
            header: {
                "content-type": "application/json"
            },
            success(res) {
                that.setData({
                    isDiscount: res.extra.can_use
                });
            }
        });
    },
    //查询满减
    refund: function() {
        var that = this;
        var items = that.data.items;
        var time_id = that.data.time_id;
        var params = {
            sku_id: items,
            time_id: time_id
        };
        if (that.data.group_id) {
            params["group_id"] = that.data.group_id;
        }
        common.request({
            endpoint: "Order/orderinfo/money_refund",
            method: "post",
            data: params,
            header: {
                "content-type": "application/json"
            },
            success(res) {
                that.setData({
                    refund: res.extra
                });
                var refund_money = that.data.refund_money;
                //refund_has不为空并且长度不为0
                //res.extra.refund_has != '' && res.extra.refund_has.length > 0 && 
                //状态为1，参加满减
                                if (res.extra.status == 1 && !!res.extra.refund_has.refund_limit) {
                    that.setData({
                        refund_money: res.extra.refund_has.refund_limit
                    });
                } else {
                    refund_money = 0;
                    that.setData({
                        refund_money: 0
                    });
                }
                var discount_price2 = that.data.discount_price2;
                let preference = parseFloat(discount_price2) + parseFloat(refund_money);
                // let preference = parseFloat(discount_price2) + parseFloat(refund_money)+parseFloat(that.data.total_mem_level_discount)
                                that.setData({
                    preference: preference
                });
                that.getIntegralDiscount();
            }
        });
    },
    //获取积分抵扣
    getIntegralDiscount: function() {
        let that = this;
        return new Promise(function(resolve, reject) {
            var items = that.data.items;
            var product_items = [];
            items.map(x => {
                product_items.push({
                    sku_id: x.sku_id,
                    num: x.num
                });
            });
            if (that.data.integral_status == 1 && that.data.isseckill != 1 && !that.data.group_id) {
                common.request({
                    endpoint: "Integral/integral_comopute/order-discount",
                    method: "post",
                    data: {
                        product_items: product_items,
                        channel: 0
                    },
                    header: {
                        "content-type": "application/json"
                    },
                    success(res) {
                        that.setData({
                            total_discount: res.extra.total_discount,
                            total_integral: res.extra.total_integral
                        });
                        that.setData({
                            integral_check: res.extra.total_discount > 0 ? 1 : 0,
                            integral_status: res.extra.total_discount > 0 ? 1 : 0
                        });
                        that.getGoods();
                    },
                    fail(err) {}
                });
            } else {
                that.setData({
                    integral_status: 0,
                    integral_check: 0
                });
                that.getGoods();
            }
        });
    },
    //判断起购价
    startBuyCondition(money) {
        var that = this;
        if (that.data.isseckill != 1) {
            //非秒杀页下单
            //判断是否达到起购价
            var moneyNum = Number(money);
            var startNum = Number(that.data.order_start);
            if (that.data.order_start_switch == "1") {
                //起购打开
                if (moneyNum >= startNum) {
                    //达到起购价
                    that.setData({
                        isPayStatus: true,
                        defferNum: "立即支付"
                    });
                } else {
                    //未达到起购价
                    that.setData({
                        isPayStatus: false,
                        defferNum: moneyNum == 0 ? "满￥" + startNum + "元起购" : "差" + (startNum - moneyNum).toFixed(2) + "元起购"
                    });
                }
            } else {
                //起购关闭
                that.setData({
                    isPayStatus: true,
                    defferNum: "立即支付"
                });
            }
        } else {
            that.setData({
                isPayStatus: true,
                defferNum: "立即支付"
            });
        }
    },
    //判断余额够不够支付和专项资金是否开启
    isCanUseBalance(totalPrice, balanceIsOpen) {
        //balanceIsOpen,余额开通1，余额未开通0
        //totalPrice实付金额
        var that = this;
        //获取支付方式状态
                var payWayList = that.data.payWayList1;
        if (balanceIsOpen == 0) {
            payWayList = payWayList.filter(item => {
                return item.payWayName != "余额";
            });
        }
        if (!that.data.features.specFund || that.data.features.specFund == 0 || that.data.features.specFund == 1 && that.data.spec_fund == 0) {
            payWayList = payWayList.filter(item => {
                return item.payWayName != "专项资金";
            });
        }
        //获取余额
                var balanceNum = that.data.balanceNum;
        console.log(totalPrice + "-" + balanceNum);
        if (parseFloat(totalPrice) <= parseFloat(balanceNum) && balanceIsOpen == 1) {
            console.log(parseFloat(totalPrice) + "-" + parseFloat(balanceNum));
            console.log("已开通");
            //余额开通并且足够支付，默认选余额支付
                        payWayList.forEach((item, index) => {
                if (item.payWayName == "余额") {
                    item.isDisabled = false;
                    item.isChecked = true;
                } else {
                    item.isDisabled = false;
                    item.isChecked = false;
                }
            });
            that.setData({
                balanceNumTip: "（余额：￥" + that.data.balanceNum + "）"
            });
        } else {
            console.log("未开通");
            //余额不足
            //余额项提示余额不足
            //显示跳转充值按钮
            //获取支付方式列表
                        console.log("ewqewqe");
            // var payWayList = that.data.payWayList;
                        payWayList.forEach((item, index) => {
                if (item.payWayName == "余额") {
                    //余额选项禁用，
                    item.isDisabled = true;
                    item.isChecked = false;
                } else if (item.payWayName == "微信支付") {
                    //默认选择第二个，
                    item.isChecked = true;
                } else {
                    item.isChecked = false;
                }
            });
            console.log(payWayList);
            that.setData({
                payWayList: payWayList,
                //更新支付列表
                balanceNumTip: "（余额不足：￥" + that.data.balanceNum + "）",
                //列表项余额不足提示
                isShowPay: false
            });
        }
        if (that.data.features.specFund == 1 && that.data.spec_fund == 1 && that.data.isseckill == 0) {
            //专项资金购买并且不是秒杀
            if (parseFloat(totalPrice) <= parseFloat(that.data.specFundNum) && that.data.isSpec_fund == 1) {
                payWayList.forEach((item, index) => {
                    if (item.payWayName == "专项资金") {
                        item.isDisabled = false;
                        item.isChecked = true;
                    } else {
                        item.isChecked = false;
                    }
                });
                that.setData({
                    specFundNumTip: "（专项资金：￥" + that.data.specFundNum + "）"
                });
            } else if (parseFloat(totalPrice) > parseFloat(that.data.specFundNum) && that.data.isSpec_fund == 1) {
                payWayList.forEach((item, index) => {
                    if (item.payWayName == "专项资金") {
                        item.isDisabled = true;
                        item.isChecked = false;
                    }
                });
                that.setData({
                    specFundNumTip: "（专项资金不足：￥" + that.data.specFundNum + "）"
                });
            } else if (that.data.isSpec_fund == 0) {
                payWayList.forEach((item, index) => {
                    if (item.payWayName == "专项资金") {
                        item.isDisabled = false;
                        item.isChecked = false;
                    }
                });
                that.setData({
                    specFundNumTip: "（专项资金：￥" + that.data.specFundNum + "）"
                });
            }
        }
        console.log(payWayList);
        that.setData({
            payWayList: payWayList
        });
    },
    toPrePaid() {
        wx.navigateTo({
            url: "../prePaid/prePaid"
        });
    },
    //获取余额
    getBalance() {
        var that = this;
        common.request({
            endpoint: "Balance/balance/mybalance",
            method: "post",
            data: {},
            success(res) {
                console.log(res, "balance");
                that.setData({
                    balanceNum: res.extra.balance,
                    balanceNumTip: "（余额：￥" + res.extra.balance + "）",
                    specFundNum: res.extra.spec_fund,
                    specFundNumTip: "（余额：￥" + res.extra.spec_fund + "）"
                });
            },
            fail(err) {
                console.log(err);
            }
        });
    },
    //余额功能是否开通
    balanceIsOpen(totalPrice) {
        console.log("请求余额开关");
        var that = this;
        common.request({
            endpoint: "Balance/balance/balance_switch",
            method: "post",
            data: {},
            success(res) {
                that.setData({
                    balanceSwitch: res.extra
                });
                if (res.extra == 1) {
                    //余额开通，判断余额是否足够支付
                    that.isCanUseBalance(totalPrice, 1);
                } else {
                    //未开通
                    that.isCanUseBalance(totalPrice, 0);
                }
            }
        });
    },
    /**
   * 
   * 筛选团长专属
   * 
   */
    filterTeamer() {
        let that = this;
        var item_idBox = that.data.idBox;
        var order_goods = that.data.order_goods;
        var platPro = that.data.platPro;
        var params = {
            data: item_idBox
        };
        if (that.data.group_id) {
            params["group_id"] = that.data.group_id;
        }
        console.log(order_goods, "dddd");
        common.request({
            endpoint: "product/cart_num",
            method: "post",
            data: params,
            success: res => {
                console.log(res, "good");
                //var stock=res.extra.default.concat(res.extra.express);
                //判断平台商品是否是团长售卖商品
                //var stock = res.extra.default;
                                var showTip = "您所购买的";
                var num = 0;
                var stock;
                var defaultPro = res.extra.default;
                var express = res.extra.express;
                //处理数据
                                if (defaultPro.length > 0) {
                    defaultPro.forEach((item, index) => {
                        item.proType = 0;
                    });
                }
                if (express.length > 0) {
                    express.forEach((item, index) => {
                        item.proType = 1;
                    });
                }
                stock = defaultPro.concat(express);
                stock.forEach((item, index) => {
                    if (item.if == 0 && item.proType == 0) {
                        num++;
                        var str = "【" + order_goods[index].name + "】";
                        showTip += str;
                    }
                });
                showTip += "不属于该" + that.data.leaderName;
                //that.confirm_order();
                //团长专属商品
                                if (num > 0) {
                    //有不属于该团长的商品，
                    wx.showModal({
                        title: "提示",
                        content: showTip,
                        showCancel: false,
                        success() {
                            //返回前一页
                            wx.navigateBack();
                        }
                    });
                } else {
                    //没有不属于该团长的商品
                    //判断弹窗,快递配送时候不显示
                    if (that.data.choose_type == 2 || !platPro || platPro.item.length == 0) {
                        //快递配送
                        that.setData({
                            confirm_lead: 0
                        });
                        //调取支付方法
                                                that.confirm_order();
                    } else {
                        that.setData({
                            confirm_lead: 1
                        });
                    }
                }
            }
        });
    },
    /**
   * 
   * 支付方式
   * 
   */
    payWay(res, order_no) {
        let that = this;
        //下单成功后，判断支付方式
        //获取支付方式列表
                var payWayList = that.data.payWayList;
        payWayList.forEach((item, index) => {
            if (item.isChecked) {
                //找到选中项
                switch (item.payWayName) {
                  case "余额":
                    //余额支付
                    console.log("余额支付");
                    //余额支付弹窗确认
                                        that.setData({
                        payName: "余额",
                        balance_confirm: 1
                    });
                    break;

                  case "微信支付":
                    //微信支付
                    wx.requestPayment({
                        timeStamp: res.pay.timeStamp,
                        nonceStr: res.pay.nonceStr,
                        package: res.pay.package,
                        signType: res.pay.signType,
                        paySign: res.pay.paySign,
                        success: function(res) {
                            console.log(res);
                            wx.showToast({
                                title: "支付成功",
                                icon: "success",
                                mask: true,
                                duration: 3e3,
                                success: function(res) {
                                    wx.showToast({
                                        title: "购买成功！",
                                        icon: "success",
                                        success: function() {
                                            common.request({
                                                endpoint: "Order/common/sync-notify",
                                                method: "post",
                                                data: {
                                                    order_no: order_no
                                                },
                                                success: res => {
                                                    setTimeout(function() {
                                                        wx.reLaunch({
                                                            url: "/pages/order_confirm/order_confirm?order_no=" + order_no
                                                        });
                                                    }, 500);
                                                },
                                                fail(err) {
                                                    wx.showModal({
                                                        title: "提示",
                                                        content: err.message
                                                    });
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        },
                        fail: function(res) {
                            wx.switchTab({
                                url: "/pages/order/order",
                                success: function(e) {
                                    let page = getCurrentPages().pop();
                                    if (page == undefined || page == null) return;
                                    page.onLoad();
                                }
                            });
                        }
                    });
                    break;

                  case "专项资金":
                    //专项资金
                    that.setData({
                        payName: "专项资金",
                        balance_confirm: 1
                    });
                }
            }
        });
    },
    updateValue(e) {
        var formConfig = this.data.formConfig;
        var field = e.detail.field;
        formConfig.forEach((item, index) => {
            if (item.formData.name == field) {
                item.formData.value = e.detail.value;
                this.setData({
                    formConfig: formConfig
                });
            }
        });
        // this.setData({
        //   formConfig
        // })
        },
    localAddress() {
        let that = this;
        common.getAppBase().then(() => {
            qqmapsdk = new QQMapWX({
                key: that.data.appBase.location_key
            });
        });
        wx.chooseLocation({
            success(res) {
                console.log(res);
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    success: function(resLocation) {
                        console.log(resLocation);
                        var areaArry = [];
                        var area = resLocation.result.address_component;
                        if (area) {
                            areaArry.push(area.province);
                            areaArry.push(area.city);
                            areaArry.push(area.district);
                        }
                        var formConfig = that.data.formConfig;
                        formConfig.forEach((item, index) => {
                            if (item.formData.name == "house_number") {
                                item.formData.value = area.street_number + res.name;
                            } else if (item.formData.name == "city") {
                                item.formData.value = areaArry;
                            }
                        });
                        that.setData({
                            formConfig: formConfig
                        });
                    }
                });
            },
            fail(err) {
                console.log(err);
            }
        });
    },
    setRecieverInfo(chooseType) {
        let that = this;
        var formConfig1 = [ {
            formType: 1,
            formData: {
                title: "收件人",
                placeholder: "请填写收件人姓名",
                important: true,
                name: "name"
            },
            formStyle: {
                padding: "0"
            }
        }, {
            formType: 1,
            formData: {
                title: "电话",
                placeholder: "请填写收件人电话",
                important: true,
                name: "phone"
            },
            formStyle: {
                padding: "0"
            }
        } ];
        var formConfig2 = [ {
            formType: 1,
            formData: {
                title: "收件人",
                placeholder: "请填写收件人姓名",
                important: true,
                name: "name"
            },
            formStyle: {
                padding: "0"
            }
        }, {
            formType: 1,
            formData: {
                title: "电话",
                placeholder: "请填写收件人电话",
                important: true,
                name: "phone"
            },
            formStyle: {
                padding: "0"
            }
        }, {
            formType: 2,
            formData: {
                title: "所在地区",
                mode: "region",
                important: true,
                name: "city",
                value: []
            },
            formStyle: {
                padding: "0"
            }
        }, {
            formType: 1,
            formData: {
                title: "详细地址",
                important: true,
                placeholder: "请填写详细地址",
                name: "house_number"
            },
            formStyle: {
                borderRadius: "0 0 8rpx 8rpx",
                padding: "0"
            }
        } ];
        if (chooseType == 1) {
            that.setData({
                formConfig: formConfig1
            });
        } else {
            that.setData({
                formConfig: formConfig2
            });
        }
        that.getInfo();
    },
    getFormId(e) {
        console.log(e.detail.formIdArry, "formIdArry");
        this.setData({
            form_id: e.detail.formIdArry
        });
    },
    //纯快递费用
    getExpressInfo() {
        let that = this;
        common.request({
            endpoint: "Order/common/express-fee",
            method: "post",
            data: {},
            success(res) {
                if (res.extra) {
                    that.setData({
                        ...res.extra
                    });
                }
                //满减条件
                                that.refund();
            }
        });
    },
    //计算平台商品
    platCountInfo(data) {
        let that = this;
        var totalPrice = 0;
        //商品总价
                if (data.length > 0) {
            data.forEach(item => {
                totalPrice += parseFloat(item.price) * item.num;
            });
        }
        that.setData({
            platTotalPrice: totalPrice
        });
    },
    //计算快递商品
    expressCountInfo(data) {
        let that = this;
        var totalPrice = 0;
        //商品总价
        //var all_price2 = that.data.all_price2;//减去满减的价格，外层做了计算
                var payExpressCost = 0;
        //计算邮费
                var express_fee = that.data.express_fee;
        //快递配送费
                var express_fms_fee = that.data.express_fms_fee;
        //满额包邮条件金额，0为不包邮
                var express_fms = that.data.express_fms;
        //满额包邮开关
                var onlyDealer = data.every((item, index) => {
            return item.supplier_type == "1";
        });
        if (onlyDealer) {
            //是否只有入驻商商品
            express_fee = 0;
            that.setData({
                onlyDealer: onlyDealer
            });
        }
        //开启满额包邮
                if (express_fms == 1) {
            if (data.length > 0) {
                data.forEach(item => {
                    if (item.is_vip && that.data.features.memberVip == 1 && that.data.vipStatus == 1 || item.is_mem_level == 1) {
                        if (item.is_mem_level == 1) {
                            totalPrice += parseFloat(item.mem_level_price) * item.num;
                        }
                        if (item.is_vip == 1) {
                            totalPrice += parseFloat(item.vip_price) * item.num;
                        }
                    } else {
                        totalPrice += parseFloat(item.price) * item.num;
                    }
                });
                if (express_fms_fee && totalPrice >= parseFloat(express_fms_fee)) {
                    //有满额包邮条件，并且满足条件
                } else {
                    payExpressCost = express_fee ? parseFloat(express_fee) : 0;
                }
                // return {
                //   expressTotalPrice: totalPrice,//商品总价
                //   expressTruePrice: truePrice,//加上配送费的价格
                // }
                        }
            //未开启满额包邮
                } else {
            if (data.length > 0) {
                payExpressCost = express_fee ? parseFloat(express_fee) : 0;
            }
        }
        that.setData({
            payExpressCost: payExpressCost.toFixed(2),
            expressTotalPrice: totalPrice
        });
        return payExpressCost;
    },
    integralChange: function() {
        let that = this;
        that.setData({
            integral_check: that.data.integral_check == 0 ? 1 : 0
        });
        let goods_money = parseFloat(that.data.all_price) - parseFloat(that.data.discount_price2) - parseFloat(that.data.refund_money);
        let preference = parseFloat(that.data.discount_price2) + parseFloat(that.data.refund_money);
        // let preference=parseFloat(that.data.discount_price2)+parseFloat(that.data.refund_money)+parseFloat(that.data.total_mem_level_discount);
                if (that.data.integral_check == 1) {
            goods_money = parseFloat(goods_money) - parseFloat(that.data.total_discount);
            preference = parseFloat(preference) + parseFloat(that.data.total_discount);
        }
        if (goods_money <= 0) {
            goods_money = .01;
        }
        goods_money = goods_money + parseFloat(that.data.other_money) + parseFloat(that.data.payExpressCost) + parseFloat(that.data.total_packing_fee);
        that.setData({
            totale_price: goods_money.toFixed(2),
            preference: preference.toFixed(2)
        });
        that.balanceIsOpen(that.data.totale_price);
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        //console.log(version);
                if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "23" || v.type == "29" || v.type == "21") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    }
});